package com.atguigu.day09;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class Flink06_SQL_Demo {
    public static void main(String[] args) {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.获取数据
        DataStreamSource<WaterSensor> waterSensorStream =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));


        //3.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //4.将流转为表
        //TODO 未注册的表
        Table table = tableEnv.fromDataStream(waterSensorStream);

        //TODO 对Table进行注册
//        tableEnv.createTemporaryView("sensor", table);

        //TODO 对流直接进行注册
        tableEnv.createTemporaryView("sensor", waterSensorStream);


        //查询未注册的表
//        Table sqlQuery = tableEnv.sqlQuery("select * from " + table);
//        sqlQuery.execute().print();

//        TableResult tableResult = tableEnv.executeSql("select * from " + table);
//        tableResult.print();

        //查询已注册的表
        tableEnv.executeSql("select * from sensor").print();


    }
}
